package eu.whowie.jast.server;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import eu.whowie.jast.remote.ModuleGroup;
import eu.whowie.jast.remote.UIRemoteInterface;
import eu.whowie.jast.remote.YastModule;
import eu.whowie.jast.remote.YastServer;

public class ServerSideClientMockup {

	private final UIRemoteInterface context;
	private JPanel removeJP;
	private JFrame frame;

	public ServerSideClientMockup(String name, UIRemoteInterface ui) {
		this.context = ui;

		frame = new JFrame(name);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JPanel mainJP = new JPanel(new BorderLayout());
		frame.getContentPane().add(mainJP);

		removeJP = new JPanel();
		mainJP.add(removeJP, BorderLayout.CENTER);

		JButton addServer = new JButton("add server");
		addServer.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				long number = (long) (100 * Math.random());
				YastServer server = new YastServer("test" + number, String
						.valueOf(number));
				String[] groupNames = { "Hardware", "Software", "System",
						"Network" };
				String[] moduleNames = { "Pavel", "Pepa", "Tomas" };

				List<ModuleGroup> moduleGroup = new ArrayList<ModuleGroup>();
				for (String gName : groupNames) {
					ModuleGroup group = new ModuleGroup();
					group.setName(gName);

					List<YastModule> modules = new ArrayList<YastModule>();
					for (String mName : moduleNames) {
						YastModule module = new YastModule();
						module.setName(gName + "-" + mName);
						modules.add(module);
					}
					group.setModules(modules);
					moduleGroup.add(group);
				}
				server.setModuleGroup(moduleGroup);

				try {
					context.connect(server);
				} catch (RemoteException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				JButton removeJB = new JButton("remove: " + number);
				removeJP.add(removeJB);
				removeJB.addActionListener(new DisconnectServer(server));

				removeJP.revalidate();
			}

		});
		mainJP.add(addServer, BorderLayout.NORTH);

	}

	private class DisconnectServer implements ActionListener {

		private final YastServer server;

		public DisconnectServer(YastServer server) {
			this.server = server;

		}

		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				context.disconnect(server);
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			removeJP.remove((JButton) e.getSource());
			removeJP.revalidate();

		}
	}

	public void show() {
		frame.setSize(640, 480);
		frame.setVisible(true);

	}

}
